const cloud = require('wx-server-sdk');
const fs = require('fs');
const path = require('path')
const PizZip = require('pizzip');
const Docxtemplater = require('docxtemplater');
const ImageModule = require('docxtemplater-image-module-free');
const axios = require('axios');

cloud.init();

// 云函数入口函数
exports.main = async (event, context) => {
  const { record,file } = event; // 接收小程序传递的数据
  try {

    // 1. 下载图片
    const tempImagePath = path.join('/tmp', `temp_${Date.now()}.png`);
    const response = await axios({
      method: 'get',
      url: record.personalKeyInformation.img,
      responseType: 'stream',
    });

    // 确保目录存在
    const tempDir = path.dirname(tempImagePath);
    if (!fs.existsSync(tempDir)) {
      fs.mkdirSync(tempDir, { recursive: true });
    }

    // 保存图片
    const writer = fs.createWriteStream(tempImagePath);
    response.data.pipe(writer);

    await new Promise((resolve, reject) => {
      writer.on('finish', resolve);
      writer.on('error', reject);
    });

    const imageModule = new ImageModule({
      centered: false,
      getImage: (tagValue) => {
        // 假设模板中的占位符是 {image}
        // console.log('处理图片标签:', tagValue);
        if (tagValue === 'img') {
          return fs.readFileSync(tempImagePath); // 返回图片 Buffer
        }
        return null;
      },
      getSize: () => [100, 150], // 图片尺寸（宽度和高度，单位：磅）
    });

    // 2. 读取模板
    // const templatePath = path.join(__dirname, 'resources', '30.传统极简简历.docx');
    const templatePath = path.join(__dirname, 'resources', file);
    const templateContent = fs.readFileSync(templatePath, 'binary');

    const doc = new Docxtemplater();
    doc.attachModule(imageModule); // 绑定图片模块
    doc.loadZip(new PizZip(templateContent));

    // 在渲染前添加调试信息
    // console.log('Template parts:', doc.getTemplatedFiles());
    // console.log('Full scope:', doc.getFullText());
    const age = calculateAge(record.personalKeyInformation.birthText)

    // 3. 设置数据（包括图片路径）
    doc.setData({
      userText: record.personalKeyInformation.userText,
      birthText: record.personalKeyInformation.birthText,
      phone: record.personalKeyInformation.phone,
      genderText: record.personalKeyInformation.genderText,
      email: record.personalKeyInformation.email,
      postText: record.personalKeyInformation.postText,
      cityText: record.personalKeyInformation.cityText,
      workText: record.personalKeyInformation.workText,
      educationText:record.personalKeyInformation.educationText,
      age: age,
      img: 'img',
      evaluation: record.evaluation.evaluation,
      education: record.education,
      workExperience: record.workExperience,
      project: record.project,
      qualificationCertificate: record.qualificationCertificate
    });

    // 3. 渲染模板
    doc.render();

    // 4. 生成二进制文件
    const wordBuffer = doc.getZip().generate({ type: 'nodebuffer' });

    fs.unlinkSync(tempImagePath); // 清理临时文件

    const uploadResult_word = await cloud.uploadFile({
      cloudPath: `generated-docs/${Date.now()}_output.docx`, // 文件名带时间戳
      fileContent: wordBuffer,
    });

    // 6. 返回文件 ID
    return {
      success: true,
      fileID: uploadResult_word.fileID,
    };
  } catch (error) {
    console.error('生成文档失败:', error);
    return {
      success: false,
      error: error.message,
    };
  }
};
// 计算年龄的函数
function calculateAge(birthday) {
  const birthDate = new Date(birthday)
  const today = new Date()

  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()

  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }

  return age
}